import React, {useEffect, useState} from "react";
import {Button, Col, DatePicker, Form, Input, InputNumber, message, Modal, Row} from "antd";
import type {Result} from "@/types/result";
import parkingChargeApi from "@/api/parkingChargeApi.ts";
import {ParkingCharge} from "@/types/resp/parkingCharge";
import ParkingAreaSelector from "@/pages/parkingArea/ParkingAreaSelector.tsx";
import RoomSelector from "@/pages/room/RoomSelector.tsx";

interface ParkingChargeAddProps {
  visible: boolean;
  id: number;
  onCloseParkingChargeAdd: () => void;
}

const ParkingChargeAdd: React.FC<ParkingChargeAddProps> = ({visible, id, onCloseParkingChargeAdd}) => {

  const [form] = Form.useForm<ParkingCharge>();
  const [messageApi, messageContextHolder] = message.useMessage();

  const rules = {
    parkingAreaNumber: [
      { required: true, message: '请输入车位号' }
    ],
    residentRoomNumber: [
      { required: true, message: '请输入单元房号' }
    ],
  };

  let parkingChargeForm: Partial<ParkingCharge> = {}

  const [title, setTitle] = useState('新增车位收费信息');

  useEffect(() => {
    if (!visible) {
      return
    }
    if (id) {
      setTitle('编辑车位收费信息')
      initParkingChargeFormById(id)
    } else {
      setTitle('新增车位收费信息')
      form.resetFields();
    }
  }, [visible]);

  const initParkingChargeFormById = async (id: number) => {
    const resp: Result<ParkingCharge> = await parkingChargeApi.findById(id)
    if (resp && resp.code === 1 && resp.data) {
      parkingChargeForm = resp.data
      form.setFieldsValue(resp.data);
    }
  }

  const onSave = async () => {
    try {
      await form.validateFields()

      let parkingCharge2Save:ParkingCharge = form.getFieldsValue()
      if (id) {
        parkingCharge2Save = Object.assign(parkingChargeForm, parkingCharge2Save)
      }
      const resp: Result<void> = await parkingChargeApi.save(parkingCharge2Save);
      if (!resp || resp.code !== 1) {
        messageApi.error('保存失败:' + (resp.msg ? resp.msg : '未知异常'));
        return
      }
      messageApi.success('保存成功');
      onBack()
    } catch (error) {
      console.error('There was an error submitting the form!', error);
    }
  };

  const onReset = () => {
    setTitle('新增车位收费信息')
    form.resetFields();
  };
  
  const [parkingAreaSelectorVisible, setParkingAreaSelectorVisible] = useState(false);
  const findParkingArea = () => {
    setParkingAreaSelectorVisible(true);
  }
  const handleParkingAreaSelected = (selectedParkingArea: { parkingAreaId?: number; parkingAreaNumber?: string; }) => {
    setParkingAreaSelectorVisible(false)
    if (selectedParkingArea && 'parkingAreaId' in selectedParkingArea) {
      form.setFieldsValue(Object.assign(form.getFieldsValue(), {
      parkingAreaId: selectedParkingArea['parkingAreaId'],
      parkingAreaNumber: selectedParkingArea['parkingAreaNumber'],
      }));
    }
  };
  const handleCloseParkingAreaSelector = () => {
    setParkingAreaSelectorVisible(false)
  };
  const [roomSelectorVisible, setRoomSelectorVisible] = useState(false);
  const findRoom = () => {
    setRoomSelectorVisible(true);
  }
  const handleRoomSelected = (selectedRoom: { residentRoomId?: number; residentRoomNumber?: string; }) => {
    setRoomSelectorVisible(false)
    if (selectedRoom && 'residentRoomId' in selectedRoom) {
      form.setFieldsValue(Object.assign(form.getFieldsValue(), {
      residentRoomId: selectedRoom['residentRoomId'],
      residentRoomNumber: selectedRoom['residentRoomNumber'],
      }));
    }
  };
  const handleCloseRoomSelector = () => {
    setRoomSelectorVisible(false)
  };

  const onBack = () => {
    onCloseParkingChargeAdd()
  };

  const addFooter = (
    <div className='custom-footer'>
      <Button type="primary" onClick={onSave}>保存</Button>
      <Button onClick={onReset} style={{marginLeft: 'var(--button-margin-left)'}}>重置</Button>
      <Button type="primary" onClick={onBack} style={{marginLeft: 'var(--button-margin-left)'}}>关闭</Button>
    </div>
  );

  return (
    <Modal title={title} open={visible} onCancel={onCloseParkingChargeAdd} width={'var(--modal-width)'}
        footer={addFooter} style={{marginTop: 'var(--modal-margin-top)'}}>
      {messageContextHolder}
      <Form form={form} name="parkingChargeForm" labelCol={{span: 6}}>
        <Row gutter={10}>
          <Col span={11}>
            <Form.Item name="parkingAreaNumber" label="车位号" rules={rules.parkingAreaNumber}>
              <Input.Search placeholder="请选择车位号" onSearch={findParkingArea} readOnly={true} />
            </Form.Item>
          </Col>
          <Col span={11}>
            <Form.Item name="residentRoomNumber" label="单元房号" rules={rules.residentRoomNumber}>
              <Input.Search placeholder="请选择单元房号" onSearch={findRoom} readOnly={true} />
            </Form.Item>
          </Col>
        </Row>
        <Row gutter={10}>
          <Col span={11}>
            <Form.Item name="licensePlate" label="车牌">
              <Input maxLength={32} placeholder="请输入车牌"/>
            </Form.Item>
          </Col>
          <Col span={11}>
            <Form.Item name="billingStartDate" label="使用开始时间">
              <DatePicker/>
            </Form.Item>
          </Col>
        </Row>
        <Row gutter={10}>
          <Col span={11}>
            <Form.Item name="billingEndDate" label="使用结束时间">
              <DatePicker/>
            </Form.Item>
          </Col>
          <Col span={11}>
            <Form.Item name="amount" label="金额">
              <InputNumber min={1} max={1} />
            </Form.Item>
          </Col>
        </Row>
        <Row gutter={10}>
          <Col span={11}>
            <Form.Item name="remark" label="备注">
              <Input maxLength={255} placeholder="请输入备注"/>
            </Form.Item>
          </Col>
        </Row>
      </Form>
      <ParkingAreaSelector visible={parkingAreaSelectorVisible} onParkingAreaSelected={handleParkingAreaSelected} onCloseParkingAreaSelector={handleCloseParkingAreaSelector} />
      <RoomSelector visible={roomSelectorVisible} onRoomSelected={handleRoomSelected} onCloseRoomSelector={handleCloseRoomSelector} />
    </Modal>
  )
}

export default ParkingChargeAdd;
